package org.sourcecode.common.cas.client;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;

public abstract class SignOutFilter extends AbstractSignFilter {

	public void init(FilterConfig filterConfig) throws ServletException {

	}

	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;

		checkSignout(request, response);
		filterExtends(request, response);

		chain.doFilter(request, response);
	}

	protected void filterExtends(HttpServletRequest request, HttpServletResponse response) {

	}

	public void destroy() {

	}

	protected void checkSignout(HttpServletRequest request, HttpServletResponse response) {

		if (!SignCheckFilter.checkRequiredFilter(request)) {
			return;
		}

		String ticketName = SignCheckFilter.TICKET;
		String cookie_ticket = CasSessionUtils.getCookie(request, ticketName);
		if (StringUtils.hasText(cookie_ticket) == false) {
			cookie_ticket = request.getParameter(ticketName);

		}

		String session_ticket = (String) request.getSession().getAttribute(SignCheckFilter.SESSION_TICKET_NAME);
		if (!StringUtils.hasText(cookie_ticket) || !cookie_ticket.equals(session_ticket)) {
			if (session_ticket != null) {
				delSession(request);
				request.getSession().removeAttribute(SignCheckFilter.SESSION_TICKET_NAME);
			}
		}
	}

	protected abstract void delSession(HttpServletRequest request);

}
